#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace Osh.ZoomPlayer
{
	public interface IZoomPlayerSection : Osh.Configuration.IConfigurationSection
	{
		string EndPoint { get; set; }
	}

	[ClassInterface(ClassInterfaceType.None)]
	public class ZoomPlayerSection : Osh.Configuration.ConfigurationSection, IZoomPlayerSection
	{
		private string _host;
		private int _port;

		public ZoomPlayerSection()
		{
		}

		[ConfigurationProperty("endPoint", DefaultValue = "localhost:4769", IsRequired = true)]
		[StringValidator(MinLength = 1)]
		public string EndPoint
		{
			get { return (string)this["endPoint"]; }
			set
			{
				ParseEndPoint(value);
				this["endPoint"] = value;
			}
		}

		private void ParseEndPoint(string endPoint)
		{
			Uri result;
			if(!Uri.TryCreate("tcp://" + endPoint, UriKind.Absolute, out result) || result.Port <= 0)
				throw new ArgumentOutOfRangeException("endPoint");
			_host = result.Host;
			_port = result.Port;
		}

		internal string Host
		{
			get
			{
				if(_host == null)
					ParseEndPoint(this.EndPoint);
				return _host;
			}
		}

		internal int Port
		{
			get
			{
				if(_port <= 0)
					ParseEndPoint(this.EndPoint);
				return _port;
			}
		}

		internal static ZoomPlayerSection Current
		{
			get { return (ZoomPlayerSection)Osh.Configuration.Configuration.Current.GetSection("zoomPlayer"); }
		}
	}
}
